﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Facebook.MiniJSON;

public class Naama : MonoBehaviour {
	
//	private static bool isInit = false;
	private Dictionary<string,object> user;
	
	void Awake() {
//		enabled = false; // "enabled" is a magic global; this lets us wait for FB before we start rendering
//		renderer.enabled = false;
		
		if( !GM.fbIsInit ) {
			FB.Init(OnInitComplete, OnHideUnity);
		}
	}

	void Start () {
		Screen.orientation = ScreenOrientation.LandscapeLeft;
	}
	
	void Update () {
//		if(!FB.IsLoggedIn) {
//			renderer.enabled = true;
//		}
		
//		Debug.Log( FB.IsLoggedIn );
		
		if( Helper.CheckTouch(gameObject) ) {
			if( !FB.IsLoggedIn ) {
				FB.Login("email", LoginCallback);
			}
		}
	}
	
	private void OnInitComplete() {
//		enabled = true; // "enabled" is a magic global; this lets us wait for FB before we start rendering
        GM.fbIsInit = true;
		
		if( FB.IsLoggedIn ) {
			GetUsername();
		}
		else {
//			renderer.enabled = true;
		}
    }

    private void OnHideUnity(bool isGameShown) {
		if (!isGameShown)    
	        Time.timeScale = 0; // pause the game - we will need to hide                                                                                                                                                         
	    else                                                                                                                       
	        Time.timeScale = 1; // start the game back up - we're getting focus again 
    }
	
	void Callback(FBResult result)
    {
        if (result.Error != null) {
			
		}
        else {
			user = Json.Deserialize( result.Text ) as Dictionary<string, object>;
			GM.userId = (string)user["id"];
			GM.first_name = (string)user["first_name"];
			GM.last_name = (string)user["last_name"];
		}
    }
	
	void LoginCallback(FBResult result) {
		if(FB.IsLoggedIn) {
//			renderer.enabled = false;
			GetUsername();
		} else {
//			renderer.enabled = true;
		}
	}
	
	// Reqest player info
	void GetUsername() {
		FB.API("/me?fields=id,first_name,last_name", Facebook.HttpMethod.GET, Callback);
	}
}
